// index.js
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0';
import {baseApi} from '../../utils/util.js';
Page({
  data: {
    motto: '章丘海河港务发展有限公司',
    userInfo: {
      avatarUrl: defaultAvatarUrl,
      nickName: '',
      phonenumber: '',
      wxUserType:'',
      unionid:'',
      openid:''
    },
    loginType:'V',
    _phonenumber:'',
    hasUserInfo: false,
    canIUseGetUserProfile: wx.canIUse('getUserProfile'),
    canIUseNicknameComp: wx.canIUse('input.type.nickname'),
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    text:'你好，此服务仅限于需要对章丘港进行公务访问的用户使用。',
    subText:'若你确实需要访问章丘港,请确认登录的微信号是否正确。'
  },
  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function() {
    
    // 查看是否授权
    console.log("// 查看是否授权... ...");
    wx.getSetting({
      success (res){
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success: function(res) {
              console.log(res.userInfo)
            }
          })
        }
      }
    })
  },
 
 
  onChooseAvatar(e) {
    const accountInfo = wx.getAccountInfoSync();
    // 必须是在用户已经授权的情况下调用
    const { avatarUrl } = e.detail
    const { nickName } = this.data.userInfo.nickName
    //debugger;
    this.setData({
      "userInfo.avatarUrl": avatarUrl,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
  },
  onInputChange(e) {
    const nickName = e.detail.value
    const { avatarUrl } = this.data.userInfo
    this.setData({
      "userInfo.nickName": nickName,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
  },
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    console.log("------------");
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },

   onGetUserInfo(e) {
    if (e.detail.userInfo) {
      // 用户授权成功
      console.log('用户信息:', e.detail.userInfo);
      const { nickName, avatarUrl, gender } = e.detail.userInfo;
      console.log('昵称:', nickName);
      console.log('头像:', avatarUrl);
      console.log('性别:', gender === 1 ? '男' : '女');
    } else {
      // 用户拒绝授权
      console.error('用户拒绝授权');
    }
  },

  onReady(){
    //this.autoLogin();
    // wx.redirectTo({
    //   url: '/pages/index/notice/index',
    // });
    var that = this;
    wx.getStorage({
      key: 'avatarUrl',
      success (res) {
        console.log(JSON.stringify(res));
        var avatarUrl = res.data;
        console.log(avatarUrl);
        if(avatarUrl){
          that.setData({
            "userInfo.avatarUrl":avatarUrl
          });
        }
      }
    });
    wx.getStorage({
      key: 'nickName',
      success (res) {
        console.log(JSON.stringify(res));
        var nickName = res.data;
        console.log("nickName->"+nickName);
        if(nickName){
          that.setData({
            "userInfo.nickName":nickName
          });
        }
      }
    });
    wx.getStorage({
      key: 'phonenumber',
      success (res) {
        console.log(JSON.stringify(res));
        var phonenumber = res.data;
        console.log("phonenumber->"+phonenumber);
        if(phonenumber){
          that.setData({
            "userInfo.phonenumber":phonenumber
          });
          that.setData({
            "_phonenumber":phonenumber
          });
        }
      }
    });
  },
  visitorLogin(){
    //访客登录
    //var url = '/pages/visitor/index';
    var url = '/pages/index/notice/index';
    this.wxLogin(url,'V');
  },
  gotoLogin(){
    var url = '/pages/index/index';
    wx.navigateTo({
      url:  url,
    });
  },
  empLogin(){
    //员工登录
    var url= '/pages/emp/list/index';
    this.wxLogin(url,'E');
  },
  doorLogin(){
    //门卫登录
    var url = '/pages/door/index';
    this.wxLogin(url,'D');
  },
  wxLogin(targetUrl,wxUserType){
    var that = this;
    that.setData({
      'userInfo.phonenumber':that.data._phonenumber,
      'userInfo.wxUserType':wxUserType
      }
      );
    if(this.data.loginType != 'V' && !this.data.userInfo.phonenumber){
        wx.showToast({
          title: '请输入手机号码',
        });
        return;
    }
    if(!this.data.userInfo.nickName){
      wx.showToast({
        title: '请选择微信昵称',
      });
      return;
    }
    if(this.data.userInfo.avatarUrl == defaultAvatarUrl){
      wx.showToast({
        title: '请选择微信头像',
      });
      return;
    }
    wx.login({
      success (res) {
        if (res.code) {
          //发起网络请求
          console.log('发起后台网络请求='+res.code);
          wx.showLoading({
            title: '登录中... ...',
          })
          wx.request({
            url: baseApi() + '/app/getWxLoginUser',
            data: {
              code: res.code
            },
            success(res) {  
              console.log('登录成功:', res.data);  
              //跳转
              //debugger;
              var openid = res.data.openid;
              wx.setStorage({
                key:"openid",
                data:openid
              });
              wx.setStorage({
                key:"avatarUrl",
                data:that.data.userInfo.avatarUrl
              });
              wx.setStorage({
                key:"nickName",
                data:that.data.userInfo.nickName
              });
              if(that.data.userInfo.phonenumber){
                wx.setStorage({
                  key:"phonenumber",
                  data:that.data.userInfo.phonenumber
                });
              }
              that.data.userInfo.openid = openid;
              wx.request({
                method: 'POST',
                url: baseApi() + '/app/wxLogin',
                data: that.data.userInfo,
                success(res){
                  wx.hideLoading();
                  //console.log(JSON.stringify(res));
                  if(res.data.code == 0){
                    wx.navigateTo({
                      url:  targetUrl,
                    });
                  }else{
                    wx.showToast({
                      title: '登录失败！'+res.data.msg,
                    });
                  }
                },
                fail(err) {
                  wx.hideLoading();
                  wx.showToast({
                    title: '登录失败！'+err,
                  });
                }
              });
            },
            fail(err) { 
              wx.showToast({
                title: '登录失败！'+err,
              });
              console.log('登录失败:', err);  
            }
          });
        } else {
          wx.showToast({
            title: '登录失败！'+res.errMsg,
          });
          console.log('登录失败！' + res.errMsg);
        }
      }
    })
  },
  otherTypeLogin(){
    console.log("otherLogin");
    this.setData({"loginType":"O"});
  },
  visitorTypeLogin(){
    console.log("otherLogin");
    this.setData({"loginType":"V"});
  }
})
